/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ufc.si.fbd.interfaces;

import java.sql.SQLException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import ufc.si.fbd.logica.dao.AtividadeDAO;
import ufc.si.fbd.logica.dao.EventoDAO;
import ufc.si.fbd.logica.entidades.Atividade;
import ufc.si.fbd.logica.entidades.Evento;

/**
 *
 * @author Guilherme
 */
public class CadastroEvento extends javax.swing.JFrame {
    private DefaultTableModel tableModel;
    private ListSelectionModel listModel;
    private int modo;
    private List<Evento> listaEventos;
    
    
    /**
     * Creates new form CadastroEvento
     */
    public CadastroEvento() {
        initComponents();
        defineModelo();
    }
    
    private void defineModelo() {
        tableModel = (DefaultTableModel) tbl_eventos.getModel();
        listModel = tbl_eventos.getSelectionModel();
        listModel.addListSelectionListener(new ListSelectionListener() {

            public void valueChanged(ListSelectionEvent e) {
                if (!e.getValueIsAdjusting()) {
                    mostraDetalheEventos();
                }
            }
        });
    }
    private void mostraDetalheEventos(){
        if(tbl_eventos.getSelectedRow()!=-1){
            int indice = tbl_eventos.getSelectedRow();
            tf_descricao.setText(listaEventos.get(indice).getDescricao());
        }
        else{
            this.tf_descricao.setText("");
        }
    }
    private void atualizaTabela() throws SQLException {
        EventoDAO eventoDAO = new EventoDAO();
        if (tf_pesquisar.getText().equals("")) {
            listaEventos = eventoDAO.listar();
        } else {
            listaEventos = eventoDAO.listar(tf_pesquisar.getText());
        }
        int numeroLinhas = tbl_eventos.getRowCount();
        for (int i = 0; i < numeroLinhas; i++) {
            tableModel.removeRow(0);
        }
        for (int i = 0; i < listaEventos.size(); i++) {
            tableModel.insertRow(i, new Object[]{listaEventos.get(i).getDescricao()});
        }
    }

    private void incluiEvento() throws SQLException {
        if (tf_descricao.getText().equals("")) {
            JOptionPane.showMessageDialog(this, "Informe a descrição do Evento!", "Erro", JOptionPane.ERROR_MESSAGE);
            tf_descricao.requestFocus();
        } else {
            Evento evento= new Evento();
            evento.setDescricao(tf_descricao.getText());

            EventoDAO eventoDAO = new EventoDAO();
            eventoDAO.salvar(evento);
            JOptionPane.showMessageDialog(this, "Evento salvo com Sucesso!", "Confirmação", JOptionPane.INFORMATION_MESSAGE);
            desabilitaCampos();
            habilitaBotoes2();
            desabilitaBotoes2();
            atualizaTabela();
        }
    }
    
    private void alteraEventos() throws SQLException {
        if (tf_descricao.getText().equals("")) {
            JOptionPane.showMessageDialog(this, "Informe o Nome do Evento!", "Erro", JOptionPane.ERROR_MESSAGE);
            tf_descricao.requestFocus();
        } else {
            Evento evento= new Evento();
           evento.setId(listaEventos.get(tbl_eventos.getSelectedRow()).getId());
           evento.setDescricao(tf_descricao.getText());
            EventoDAO eventoDAO = new EventoDAO();
                eventoDAO.salvar(evento);
                JOptionPane.showMessageDialog(this, "Evento alterado com Sucesso!", "Confirmação", JOptionPane.INFORMATION_MESSAGE);
                desabilitaCampos();
                habilitaBotoes2();
                desabilitaBotoes2();
                atualizaTabela();   
        }
    }

    private void excluiEventos() throws SQLException {
        EventoDAO eventoDAO = new EventoDAO();
        AtividadeDAO atvDAO = new AtividadeDAO();
        List<Atividade> atvs = atvDAO.listar(listaEventos.get(tbl_eventos.getSelectedRow()));
        if(!atvs.isEmpty()){
            int resposta = JOptionPane.showConfirmDialog(this, "Existe atividades cadastradas nesse evento, deseja realmente Exclui-lo ?", "Confirmação", JOptionPane.YES_NO_OPTION);
            if (resposta == JOptionPane.YES_OPTION) {
            eventoDAO.remover(listaEventos.get(tbl_eventos.getSelectedRow()).getId());
            JOptionPane.showMessageDialog(this, "Evento Excluido com Sucesso!", "Confirmação", JOptionPane.INFORMATION_MESSAGE);
            atualizaTabela();
            }
        }else{
            int resposta = JOptionPane.showConfirmDialog(this, "Deseja realmente Excluir esse Evento?", "Confirmação", JOptionPane.YES_NO_OPTION);
            if (resposta == JOptionPane.YES_OPTION) {
                eventoDAO.remover(listaEventos.get(tbl_eventos.getSelectedRow()).getId());
                atualizaTabela();
            }
        }
    }
    
    private void habilitaCampos() {
        tf_descricao.setEditable(true);
        tf_descricao.requestFocus();
        tf_pesquisar.setEditable(false);
        jb_pesquisar.setEnabled(false);
    }

    private void desabilitaCampos() {
        tf_descricao.setEditable(false);
        tf_pesquisar.setEditable(true);
        jb_pesquisar.setEnabled(true);
    }

    private void habilitaBotoes() {
        jb_salvar.setEnabled(true);
    }

    private void desabilitaBotoes() {
        jb_alterar.setEnabled(false);
        jb_excluir.setEnabled(false);
        jb_novo.setEnabled(false);
    }

    private void habilitaBotoes2() {
        jb_alterar.setEnabled(true);
        jb_excluir.setEnabled(true);
        jb_novo.setEnabled(true);
    }

    private void desabilitaBotoes2() {
        jb_salvar.setEnabled(false);
    }

    private void limpaCampos() {
        tf_descricao.setText("");

    }

    
    
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tbl_eventos = new javax.swing.JTable();
        jb_novo = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        tf_descricao = new javax.swing.JTextPane();
        jSeparator1 = new javax.swing.JSeparator();
        jSeparator2 = new javax.swing.JSeparator();
        jb_salvar = new javax.swing.JButton();
        jb_alterar = new javax.swing.JButton();
        jb_excluir = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        tf_pesquisar = new javax.swing.JTextField();
        jSeparator3 = new javax.swing.JSeparator();
        jb_pesquisar = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Cadastro de Eventos");

        tbl_eventos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Descrição"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        jScrollPane1.setViewportView(tbl_eventos);

        jb_novo.setText("Novo");
        jb_novo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jb_novoActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel1.setText("Descrição do Evento:");

        tf_descricao.setEditable(false);
        jScrollPane2.setViewportView(tf_descricao);

        jb_salvar.setText("Salvar");
        jb_salvar.setEnabled(false);
        jb_salvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jb_salvarActionPerformed(evt);
            }
        });

        jb_alterar.setText("Alterar");
        jb_alterar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jb_alterarActionPerformed(evt);
            }
        });

        jb_excluir.setText("Excluir");
        jb_excluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jb_excluirActionPerformed(evt);
            }
        });

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
        jLabel3.setText("Pesquisar:");

        jb_pesquisar.setText("Consultar");
        jb_pesquisar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jb_pesquisarActionPerformed(evt);
            }
        });

        jLabel4.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
        jLabel4.setText("Cadastro de Eventos");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSeparator1)
            .addComponent(jSeparator2)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jb_novo)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jb_salvar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jb_alterar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jb_excluir))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(tf_pesquisar)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jb_pesquisar))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 598, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jLabel1)
                                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 598, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(0, 0, Short.MAX_VALUE)))))
                .addContainerGap())
            .addComponent(jSeparator3)
            .addGroup(layout.createSequentialGroup()
                .addGap(185, 185, 185)
                .addComponent(jLabel4)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel3)
                        .addComponent(tf_pesquisar, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jb_pesquisar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jb_novo, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jb_salvar, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jb_alterar, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jb_excluir, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-634)/2, (screenSize.height-495)/2, 634, 495);
    }// </editor-fold>//GEN-END:initComponents

    private void jb_novoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jb_novoActionPerformed
       modo = 0;// 0 - salvar incluir
        habilitaCampos();
       desabilitaBotoes();
       habilitaBotoes();
       limpaCampos();
    }//GEN-LAST:event_jb_novoActionPerformed

    private void jb_salvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jb_salvarActionPerformed
        try {
            if(modo == 0){
            incluiEvento();
            }else if(modo==1){
                alteraEventos();
            }
        } catch (SQLException ex) {
            Logger.getLogger(CadastroEvento.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jb_salvarActionPerformed

    private void jb_alterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jb_alterarActionPerformed
    if (tbl_eventos.getSelectedRow() != -1) {
        modo = 1;// 1 salvar - alteração    
        habilitaCampos();
            desabilitaBotoes();
            habilitaBotoes();
            tf_descricao.requestFocus();
        } else {
            JOptionPane.showMessageDialog(this, "Selecione um Evento na Lista", "Erro", JOptionPane.INFORMATION_MESSAGE);
        }
    }//GEN-LAST:event_jb_alterarActionPerformed

    private void jb_excluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jb_excluirActionPerformed
    if (tbl_eventos.getSelectedRow() != -1) {
            try {
                excluiEventos();
            } catch (SQLException ex) {
                Logger.getLogger(CadastroEvento.class.getName()).log(Level.SEVERE, null, ex);
            }
     }else {
                 JOptionPane.showMessageDialog(this, "Selecione um Evento na lista!", "Erro", JOptionPane.ERROR_MESSAGE);
            }
    }//GEN-LAST:event_jb_excluirActionPerformed

    private void jb_pesquisarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jb_pesquisarActionPerformed
        try {
            atualizaTabela();
        } catch (SQLException ex) {
            Logger.getLogger(CadastroEvento.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jb_pesquisarActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(CadastroEvento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(CadastroEvento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(CadastroEvento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(CadastroEvento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new CadastroEvento().setVisible(true);
            }
        });
        /* Create and display the form */
  
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JSeparator jSeparator3;
    private javax.swing.JButton jb_alterar;
    private javax.swing.JButton jb_excluir;
    private javax.swing.JButton jb_novo;
    private javax.swing.JButton jb_pesquisar;
    private javax.swing.JButton jb_salvar;
    private javax.swing.JTable tbl_eventos;
    private javax.swing.JTextPane tf_descricao;
    private javax.swing.JTextField tf_pesquisar;
    // End of variables declaration//GEN-END:variables
}
